﻿<template>
    <full-screen-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1300"
        destroy-on-close
        :close-on-click-modal="false"
        @closed="$emit('closed')"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="申请单位：">
                        {{entityObj.storeName}}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="申请人：">
                        {{entityObj.createName}}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="申请时间：">
                        {{entityObj.afterOrderTime}}
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="退换货清单：" prop="afterOrderItems">
                        <el-button type="primary" size="small" @click="addMaterial()" >新增物料</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="">
                        <el-table :data="entityObj.afterOrderItems" border style="width: 100%" show-summary :summary-method="getSummaries">
                           
                            <!-- <el-table-column label="物料编码" width="100">
                                    <template #default="scope">{{scope.row.materialCode}}</template>
                            </el-table-column> -->
                            
                            <el-table-column label="物料名称" width="180">
                                <template #default="scope">
                                    <div v-if="scope.row.applyOrderId>0 && scope.row.price<=0">
                                        {{scope.row.materialName}}   <el-tag type="danger" effect="light">赠</el-tag>
                                    </div>
                                    <div v-else>
                                        <div style="color: #318cf2; cursor: pointer;" @click="handlePreview(scope.row)">
                                            {{scope.row.materialName}}
                                        </div>
                                        
                                    </div>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column label="分类" width="100">
                                <template #default="scope">{{scope.row.materialTypeName}}</template>
                            </el-table-column> -->
                            <el-table-column label="规格" width="100">
                                <template #default="scope">{{scope.row.materialSpecs}}</template>
                            </el-table-column>
                            <el-table-column label="单位" width="70">
                                <template #default="scope">{{scope.row.newUnitName}}</template>
                            </el-table-column>
                            <el-table-column label="供应商" width="230" >
                                <template #default="scope">
                                    <el-form>
                                        <el-select placeholder="---请选择供应商---" v-model="scope.row.supplier" :disabled="scope.row.isDisable" style="width:100%" @change="onSupplierChange(scope.row)">
                                            <el-option
                                                v-for="item in scope.row.materialSuppliers"
                                                :key="item.supplierOrgType+'_'+ item.supplierId"
                                                :label="item.supplierFullName"
                                                :value="item.supplierOrgType+'_'+ item.supplierId"
                                            />
                                        </el-select>
                                    </el-form>
                                </template> 
                            </el-table-column>
                            <el-table-column label="销售单价" width="100" >
                                <template #default="scope"> 
                                  
                                    <span v-if="scope.row.afterOrderType==0">
                                        --
                                    </span>
                                    <el-form v-if="scope.row.afterOrderType==1">
                                        <el-input v-model="scope.row.price" type="text"/>
                                    </el-form>
                                </template>
                            </el-table-column>
                            <el-table-column label="采购单价" width="100" >
                                <template #default="scope"> 
                                    <span v-if="scope.row.afterOrderType==0">
                                        --
                                    </span>
                                    <el-form v-if="scope.row.afterOrderType==1">
                                        <el-input v-model="scope.row.purchasePrice" type="text"/>
                                    </el-form>
                                </template>
                            </el-table-column>
                            <el-table-column label="应退门店" width="100"  prop="returnAmount">
                                <template #default="scope">
                                    <span v-if="scope.row.afterOrderType==0">--</span>
                                    <span v-if="scope.row.afterOrderType==1">{{scope.row.confirmQty * scope.row.price}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="应退供应商" width="100"  prop="purchaseReturnAmount">
                                <template #default="scope">
                                    <span v-if="scope.row.afterOrderType==0">--</span>
                                    <span v-if="scope.row.afterOrderType==1">{{scope.row.confirmQty * scope.row.purchasePrice}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="破损处理" width="130" prop="afterOrderType">
                                <template #default="scope">
                                    <el-form >
                                        <el-select placeholder="处理方式" v-model="scope.row.afterOrderType" style="width: 100px">
                                            <el-option label="补发" :value="0"/>
                                            <el-option label="退货" :value="1"/>
                                        </el-select>
                                    </el-form>
                                </template>
                            </el-table-column>
                            <el-table-column label="申请数量" width="130" prop="qty">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.qty"
                                        style="width: 100%"
                                        :step="1"
                                        :min="1"
                                        controls-position="right"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="接单数量" width="130" prop="confirmQty">
                                <template #default="scope">
                                    <el-form >
                                        <el-input-number
                                            v-model="scope.row.confirmQty"
                                            style="width: 100%"
                                            :step="1"
                                            :max="scope.row.qty"
                                            :min="1"
                                            controls-position="right"
                                        ></el-input-number>
                                    </el-form>
                                </template>
                            </el-table-column>
                            <el-table-column label="要货编号" width="200">
                                <template #default="scope">
                                    <el-form>
                                        <sc-apply-order-select
                                            style="width:100%"
                                            placeholder="---请选择要货单---"
                                            ref="applyOrderSelect"
                                            :props="applyOrderProps"
                                            :defaultQueryList="{storeId:this.entityObj.storeId,materialItemId:scope.row.materialItemId}"
                                            :selectKeyValue="'applyOrderId'"
                                            
                                            @fatherMethod="applyOrderSelectProcess"
                                            :multiple="false"
                                            :pageId="scope.row.afterOrderItemId"
                                        ></sc-apply-order-select>   
                                    </el-form>
                                </template>
                            </el-table-column>
                           
                            
                           
                            <el-table-column label="破损照片" width="150" >
                                <template #default="scope">
                                        <sc-upload-multiple 
                                            v-model="scope.row.images"
                                            :objName="'Supply/AfterOrder'" 
                                            :uploadType="'OSS'" 
                                            :bucketName="'jtmc'" 
                                            :limit="5"
                                           
                                             />
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" width="150" >
                                <template #default="scope">
                                    <el-input v-model="scope.row.remarks" style="width: 100%" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作">
                                <template #default="scope">
                                    <el-button
                                        type="danger"
                                        size="small"
                                        @click="deleteRow(scope.$index, scope.row)"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                    
                </el-col>
            </el-row>
           
        </el-form>
        <el-row>
            <el-col :span="24">
                <el-form-item label-width="120px" label="门店备注：">
                    <el-input v-model="this.entityObj.remarks" type="textarea" :rows="2" :disabled="true"/>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
                <el-form-item label-width="120px" label="审核备注：">
                    <el-input v-model="auditRemarks" type="textarea" :rows="1" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
                <el-form-item label-width="120px" label="退回仓库：">
                    <el-radio-group v-model="this.entityObj.isBack">
                        <el-radio :label="0">否</el-radio>
                        <el-radio :label="1">是</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row v-if="this.entityObj.isBack==1">
            <el-col :span="24">
                <el-form-item label-width="120px" label="选择仓库：">
                    <el-select placeholder="---请选择仓库---" v-model="this.entityObj.warehouseId" style="width:300px">
                        <el-option
                            v-for="item in this.entityObj.purchaseUnityWarehouses"
                            :key="item.warehouseId"
                            :label="item.warehouseName"
                            :value="item.warehouseId"
                        />
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button  type="danger"  :loading="isSaveing"  @click="opNoPass()">退 回</el-button>
            <el-button  type="primary"  :loading="isSaveing" @click="opPass()">保 存</el-button>
        </template>
        <template>
            <el-dialog
                v-model="materialVisible"
                title="选择收货订单物料"
                :width="1300"
                :center="true"
                append-to-body
                style="height: 480px"
            >
                <el-row>
                    <sc-task-order-item-choice
                        ref="scTaskOrderItemChoice"
                        :storeId="this.entityObj.storeId"
                    ></sc-task-order-item-choice>
                </el-row>
                <template #footer>
                    <el-button @click="materialVisible = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setTaskOrderItemChoice">确定</el-button>
                </template>
            </el-dialog>
        </template>

       <!-- 预览组件 -->
       <el-image-viewer v-if="showImage" @close="closeViewer" :url-list="srcList" />


    </full-screen-dialog>
</template>

<script>
import tool from "@/utils/tool";
export default {
    emits: ["success", "closed"],
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "补发/退货申请",
                Edit: "编辑",
                Show: "审核补发/退货申请",
            },
            entityObj: {
                
                afterOrderItems:[],
                purchaseUnityWarehouses:[],
                isBack:0,
                warehouseId:0
            },
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            defaultQueryList:{},
            afterOrderId:0,//售后ID
            auditRemarks:"",//审核备注
            auditDate:"",//审核时间
            optionsSuppliers:[],//供应商列表
            orgId:0,//门店ID
            applyOrderProps: {
                label: "applyOrderCode",
                value: "applyOrderId",
            },
             //预览图片
             previewUrl: [],
            //预览图片列表
            srcList: [],
            showImage: false,
        };
    },

    methods: {
        //显示=
        open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
       
        summaryFun(val){
            const { columns, row } = val;
            const sums = [];

            columns.forEach((item, index) => {
                if (index === 1) {
                    var totalAmount=0;
                    this.entityObj.afterOrderItems.forEach((item) => {
                        totalAmount+=item.price * item.qty
                    });
                     sums[index] = '总计：'+totalAmount;
                    return;
                }
            });
            return sums;
        },
        //获取表格的合计行数据
        getSummaries(param){
            const{ columns,data}=param;
            const sums=[];
            columns.forEach((column,index)=>{
                if (index === 0) {
                    sums[index] = '合计'
                    return;
                }
                const values=data.map(item=>Number(item[column.property]));
               
                if(column.property=='qty'){
                    if(!values.every(item=>isNaN(item))){
                        const total = values.reduce((a, b) => a + b, 0)
                        sums[index] = total
                    }
                }
                else if(column.property=='confirmQty'){
                    if(!values.every(item=>isNaN(item))){
                        const total = values.reduce((a, b) => a + b, 0)
                        sums[index] = total
                    }
                }
                else if(column.property=='returnAmount')
                {
                    var totalAmount=0;
                    this.entityObj.afterOrderItems.forEach((item) => {
                        totalAmount+=item.price * item.confirmQty
                    });
                    sums[index]=totalAmount
                    
                }else if(column.property=='purchaseReturnAmount')
                {
                    var totalAmount=0;
                    this.entityObj.afterOrderItems.forEach((item) => {
                        totalAmount+=item.purchasePrice * item.confirmQty
                    });
                    sums[index]=totalAmount
                    
                }
                
            });
            return sums;
        },
        //表单注入数据
        async setData(data) {
            this.afterOrderId=data.afterOrderId;
            this.entityObj.remarks=data.remarks;
            this.entityObj.createName = data.createName;
            this.entityObj.storeId = data.storeId;
            this.entityObj.storeName = data.storeName;
            this.entityObj.afterOrderTime = data.afterOrderTime;
            this.entityObj.isBack = data.isBack;
            this.entityObj.warehouseId = data.warehouseId;
            this.entityObj.purchaseUnityWarehouses=data.purchaseUnityWarehouses;
            console.log("data",data);
            if (data.afterOrderId) {
                try {
                    var returnValue = await this.$API.auth.GetProcessApi.get(
                        `after-order/${data.afterOrderId}`,
                        { }
                    );
                    if (returnValue.status == 200) {
                        this.entityObj.afterOrderItems =returnValue.response;
                        console.log("明细",this.entityObj.afterOrderItems);
                    } else {
                        this.$message.error("操作失败:" + returnValue.msg);
                    }
                } catch (error) {
                    this.loading = false;
                    return false;
                }
            }
        },

        //不通过
        async opNoPass(){
            this.setStatus(2);
        },
        //通过
        async opPass(){
            //var unPrice = this.entityObj.afterOrderItems.filter(item => item.price==0);
            //if(unPrice.length>0)
            //{
                //this.$message.error("请先输入单价");  
                //return;
            //}
           
            if(this.entityObj.isBack==0)
            {
                var unBindSuppliers = this.entityObj.afterOrderItems.filter(item => item.supplierId==0 || item.supplierId==null);
                console.log("未绑定供应商",unBindSuppliers);
                if(unBindSuppliers.length>0)
                {
                    this.$message.error("请先绑定供应商");  
                    return;
                }
                this.$confirm(`审核通过后，将会自动下单至对应供应商，进行补发或退货处理，确认审核通过吗？？`, '提示', {type: 'warning'}).then(() => {
                    this.setStatus(1);
                });
            }else
            {
                this.$confirm(`确认退回到采购仓库吗？？`, '提示', {type: 'warning'}).then(() => {
                    this.setStatus(1);
                });
            }
            
           
        },
        //设置状态
        async setStatus(status){
            try {
                    var returnValue = await this.$API.auth.PostProcessApi.post("after-order/state",{ 
                        afterOrderId: this.afterOrderId,
                        status:status,
                        AuditRemarks:this.auditRemarks,
                        afterOrderItems:this.entityObj.afterOrderItems,
                        isBack:this.entityObj.isBack,
                        warehouseId:this.entityObj.warehouseId,
                    });
                    if (returnValue.status == 200) {
                        this.$message.success("操作成功");
                        this.visible=false;
                        this.$emit("fatherMethod");
                    } else {
                        this.$message.error("操作失败:" + returnValue.msg);
                    }

                } catch (error) {
                    this.loading = false;
                    this.visible=false;
                }
        },
        //供应商选择
        onSupplierChange(row){
            const supplier= row.supplier.split('_');
            if(supplier&&supplier.length==2){
                var supplierInfo= row.materialSuppliers.find((p)=>p.supplierOrgType==supplier[0]&&p.supplierId==supplier[1]);
                if(supplierInfo)
                {
                    row.supplierOrgType=supplierInfo.supplierOrgType;
                    row.supplierId=supplierInfo.supplierId;
                    row.price=supplierInfo.deliveryPrice;
                    row.purchasePrice=supplierInfo.purchasePrice;
                }
            }
            console.log("row",row);
        },
        //要货选择
        async applyOrderSelectProcess(rowData,rowId) {
            if (rowData) {
                console.log("要货选择",rowData)
                this.entityObj.afterOrderItems.filter(p=>p.afterOrderItemId==rowId).map(p=>{
                    p.applyOrderId = rowData.applyOrderId;
                    p.applyOrderCode = rowData.applyOrderCode;
                    p.applyOrderItemId =rowData.applyOrderItemId;
                    p.price=rowData.applyPrice;
                    p.purchasePrice=rowData.purchasePrice;
                    p.supplierId=rowData.supplierId;
                    //禁用供应商选择
                    if(rowData.supplierId>0)
                    {
                        p.isDisable=true;
                    }
                });
               
            }
        },
        //图片预览
        handlePreview(row) {
            if (!row.materialImages || row.materialImages.length == 0) {
                return;
            }
            this.previewUrl = row.materialImages[0]; // 设置当前预览的图片 URL
            this.srcList = row.materialImages; // 设置预览列表
            this.showImage = true; // 显示 el-image

        },
        closeViewer(){
            this.showImage = false; 
        },
        async initOptions() {
           
           
        },

    },
    async mounted() {
        this.orgId = tool.data.get("USER_INFO").OrgId;
        await this.initOptions();
        //await this.getSupplier();
        this.auditDate = tool.formatDate(new Date());
    },
};
</script>
<style scoped>

::v-deep .el-upload--picture-card{
    width: 50px;
    height: 50px;
}
::v-deep .el-upload{
    width: 50px;
    height: 50px;
    line-height: 50px;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item{
    width: 50px;
    height: 50px;
    line-height: 50px;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item-thumbnail{
    width: 50px;
    height: 50px;
    line-height: 50px;
}
</style>
